<template>
    <div>
        <el-row style="background: #eee; padding:5px 10px;">
            <el-col :span="18">
                Day {{keyIdx+1}}: <el-date-picker
                v-model="groupData.scheduled_at"
                type="date"
                :placeholder="$t('placeholder.select')" 
                size="mini"
                value-format="yyyy-MM-dd" 
                @change="changeScheduled">
                </el-date-picker> 
            </el-col>
            <el-col :span="6">
                <el-select v-model="groupData.group_id" class="filter-item" :placeholder="$t('placeholder.select')"  style="width: 180px;" size="mini"  @change="changeGroup($event)">
                    <el-option v-for="(item, ind) in groupOptions" :key="ind" :label="item.name" :value="item.id" />
                </el-select>
            </el-col>
        </el-row>
        <div>
            <el-row :gutter="10" style="display: inline-block; margin-top:10px; width: 80%;">
            <product-li v-for="(item, t) in groupData.product" :key="t"  :item-obj="item" :product-list="productOptions" @change-product="changeProduct" :idx="t"></product-li>
            <!--<el-col v-for="(item, t) in groupData.product" :key="t" :span="2">
                 <img class="cart-img" :title="item.product_name" :src="item.product_mphoto_url? item.product_mphoto_url : getEmptyImg()" style="width:60px">
                <div>{{item.product_scode ? item.product_scode : '--'}}</div>
                <div>{{item.product_scode ? item.product_scode : '--'}}</div>
                <div>{{item.product_name ? item.product_name : '--'}}</div>
                <el-select v-model="item.product_id"  placeholder="Pick a package" size="mini" class="cleanse-obj"  @change="changeProduct($event)">
                    <el-option
                    v-for="prodct in productOptions"
                    :key="prodct.id"
                    :label="prodct.name"
                    :value="prodct.id">
                    </el-option>
                </el-select>
                <div>
                    <input type="hidden" v-model="item.product_id" name="product_id[]">
                    <el-select v-model="item.qty" name="qty[]" class="filter-item" style="width: 60px;" size="mini" @change="changeQty">
                        <el-option v-for="(option, dex) in quantOptions" :key="dex" :label="option" :value="option" />
                    </el-select>
                </div>
            </el-col> -->
            
            </el-row>
            <div style="float:right; width: 17%;">
                <div><span>Location</span></div>
                <!-- <el-select v-model="groupData.location_id" class="filter-item" :placeholder="$t('placeholder.select')"  style="width: 100px;" size="mini"  @change="changeLocation">
                    <el-option v-for="(option, index) in locations" :key="index" :label="option.name" :value="option.id" />
                </el-select> -->
                <div>
                    <el-select v-model="groupData.location_name" value-key="id" placeholder="Please Select..." @change="changeLocation($event)">
                        <el-option-group
                        v-for="group in locationOptions"
                        :key="group.id"
                        :label="group.name"
                        :value="group.id">
                        <el-option
                            v-for="item in group.child"
                            :key="item.id"
                            :label="item.name"
                            :value="item">
                        </el-option>
                        </el-option-group>
                    </el-select>
                    <!-- <span class="help-blocker hid help-main-location red">Please select a delivery location.</span> -->
                </div>
                <div class="delivery-zone" v-show="isShow">
                    <label class="label label-warning">To</label>
                    <div class="clearfix"></div>
                    <div class="">
                        <el-select v-model="groupData.area_region_id" placeholder="Please Select District" @change="changeArea($event)">
                            <el-option
                            v-for="item in locations"
                            :key="'h' + item.id"
                            :label="item.name + '（' + item.freight + '）'"
                            :value="item.id">
                            </el-option>
                        </el-select>
                        <!-- <span class="help-blocker hid red help-delivery-district">Please select a district.</span> -->
                        <el-input type="hidden" class="home_delivery_freight" v-model="groupData.freight" ></el-input>
                    </div>
                    <label class="label label-warning">Address</label>
                    <div class="">
                        <el-input class="home_delivery_address" v-model="groupData.address" placeholder="Detail Address" ></el-input>
                        <!-- <span class="help-blocker red hid help-detail-address">Please fill in the home detail address</span> -->
                    </div>
                </div>
            </div>
        </div>
        <el-row>
            <el-col>
                <el-button v-if="groupData.product.length < 10 || groupData.group_id === customGroupId" style="font-size:20px;" type="text" @click="addItem()" class="el-icon-circle-plus-outline" ></el-button>
                <el-button style="font-size:20px;" type="text" @click="delItem()" class="el-icon-remove-outline" ></el-button>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import { fetchList as fetchGroupList } from '@/api/group'
import ProductList from '@/components/GroupProduct/ProductList'
import ProductLi from '@/components/GroupProduct/ProductLi'
import i18n from '@/lang/index'
/* import { formatData } from '@/utils' */
import { fetchAll } from '@/api/location'
export default {
    components: { ProductList, ProductLi },
    props: {
        orderData: {
            type: Object,
            default () {
                return {
                    location_id: '',
                    area_region_id: '',
                    home_locations: [],
                    scheduled_at: ''
                }
            }
        },
        idx: Number,
        keyIdx: Number,
        locationOptions: Array,
        homeLocations: {
            type: Array,
            default () {
                return []
            }
        },
        products: Array,
        productOptions: Array,
        groupOptions: Array,
        startDate:  {
            type: [Date, String],
            default () {
                return ''
            }
        },
        homeList: Array,
        customGroupId: Number
    },
    data () {
        return {
            groupData: {
                area_region_id: '',
                scheduled_at: ''
            },
            productAll: JSON.parse(JSON.stringify(this.products)),
            quantOptions: [0, 1, 2, 3],
            isFirst: true,
            isAddFirst: true,
            locations: JSON.parse(JSON.stringify(this.orderData.home_locations ? this.orderData.home_locations : [])),
            isChange: false
        }
    },
    created() {
        this.groupData = JSON.parse(JSON.stringify(this.orderData))
        this.groupData.area_region_id = this.groupData.area_region_id || ''
        console.log(this.groupData.scheduled_at)
        if (!this.groupData.scheduled_at) {
            let date = new Date(this.startDate)
            date.setTime(date.getTime() + 3600 * 1000 * 24 * (this.keyIdx))
            this.groupData.scheduled_at = date
        }
        console.log(this.groupData.scheduled_at)
        if(!this.groupData.location_id){
            this.isFirst = false
            this.isAddFirst = false
        }
    },
    computed: {
        isShow() {
            let iss = false
            const val = this.groupData.location_id
            if (val && this.homeList.indexOf(val) > -1) {
                iss = true
            }
            return iss
        }
    },
    watch: {
        orderData: function (val) {
            const _this = this
            this.groupData = JSON.parse(JSON.stringify(val))
            if (!this.groupData.scheduled_at) {
                let date = new Date(this.startDate)
                date.setTime(date.getTime() + 3600 * 1000 * 24 * (this.keyIdx))
                this.groupData.scheduled_at = date
            }
            if (this.groupData.location_id) {
                let params = {
                    pid: this.groupData.location_id
                }
                fetchAll(params).then((res) => {
                    _this.locations = JSON.parse(JSON.stringify(res.data.data))
                    _this.groupData.home_locations = _this.locations
                    _this.groupData.area_region_id = val.area_region_id
                })
            }
            // this.locations = JSON.parse(JSON.stringify(val.home_locations ? val.home_locations : []))
        },
        'startDate': function (val) {
            let date = new Date(val)
            date.setTime(date.getTime() + 3600 * 1000 * 24 * (this.keyIdx))
            this.groupData.scheduled_at = date
        },
        /* 'groupData.location_id': function (val) {
            let _this = this
             if (this.isShow) {
                let params = {
                    pid: val
                }
                fetchAll(params).then((res) => {
                    _this.locations = res.data.data
                    // _this.groupData.home_locations = res.data.data
                    if (_this.isChange) {
                        _this.groupData.area_region_id = ''
                    } else {
                        _this.groupData.area_region_id = _this.orderData.area_region_id
                    }
                    if(!_this.isFirst){
                        _this.$emit('delivery-change', _this.keyIdx, val, _this.isShow, _this.groupData)
                        _this.groupData.area_region_id = ''
                    }else {
                        _this.isFirst = false
                    }
                })
            } else {
                if(!_this.isFirst){
                    _this.$emit('delivery-change', _this.keyIdx, val, _this.isShow, _this.groupData)
                    _this.groupData.area_region_id = ''
                }else {
                    _this.isFirst = false
                }
            }
        },
        'groupData.area_region_id': function (val) {
            var freight = 0
            let _this = this
            for (var i=0; i < this.locations.length; i++) {
                if (this.locations[i].id === val) {
                    freight = this.locations[i].freight
                    this.groupData.delivery = freight
                }
            }
            this.$nextTick(() => {
                _this.$emit('area-change', this.keyIdx, val, freight, this.isAddFirst, this.groupData)
            })
            this.isAddFirst = false
            // this.isAddFirst = false
        }, */
        'groupData.address': function (val) {
            // console.log(val)
            this.$emit('address-change', this.keyIdx, val)
        }
    },
    methods: {
        getEmptyImg () {
            return require('../../assets/empty01.jpg')
        },
        /* changeProduct (id) {
            let val ={}
            for (let i=0; i<this.productList.length; i++) {
                if(this.productList[i].id === id) {
                    val = JSON.parse(JSON.stringify(this.productList[i]))
                }
            }
            let data = {}
            data.product_name = val.name
            data.product_scode = val.scode
            data.product_lang = val.lang
            data.product_id = val.id
            data.product_mphoto = val.mphoto
            data.product_mphoto_url = val.mphoto_url,
            data.dqty = 1
            data.mqty = 1
            this.item = data
            this.$emit('change-product', data, this.idx)
        }, */
        addItem() {
            let data = JSON.parse(JSON.stringify(this.products[0]))
            data.qty = data.qty || data.qty === 0 ? data.qty : data.dqty || data.dqty === 0 ? data.dqty : 1
            delete data.product_lang
            this.groupData.product.push(data)
        },
        delItem() {
            if (this.groupData.product.length > 0) {
                this.groupData.product.pop()
            }
        },
        changeLocation(val) {
            const _this = this
            this.isChange = true
            this.groupData.location_id = val.id
            this.groupData.location_name = val.name
            this.groupData.area_region_id = ''
            this.groupData.delivery = 0
            this.groupData.freight = 0
            if (val.id) {
                let params = {
                    pid: val.id
                }
                fetchAll(params).then((res) => {
                    _this.locations = JSON.parse(JSON.stringify(res.data.data))
                    _this.groupData.home_locations = _this.locations
                    if (!_this.isShow) {
                        _this.groupData.delivery = 0
                        _this.groupData.freight = 0
                        _this.groupData.area_region_id = ''
                        _this.groupData.area_region_name = ''
                    }
                })
            }
            this.$emit('delivery-change', this.keyIdx, val.id, this.isShow, this.groupData)
        },
        changeArea(val) {
            var freight = 0
            let _this = this
            for (var i=0; i < this.locations.length; i++) {
                if (this.locations[i].id === val) {
                    freight = this.locations[i].freight
                    this.groupData.delivery = freight
                    this.groupData.freight = freight
                    this.groupData.area_region_name = this.locations[i].name
                }
            }
            this.$nextTick(() => {
                _this.$emit('area-change', this.keyIdx, val, freight, this.isAddFirst, this.groupData)
            })
        },
        changeQty() {
            this.$emit('change-group', this.groupData, this.keyIdx)
        },
        changeScheduled() {
            console.log(2222)
            console.log(this.groupData)
            this.$emit('change-group', this.groupData, this.keyIdx)
        },
        changeProduct (data, index) {
            this.groupData.product[index] = data
            this.groupData.group_id = this.customGroupId
            this.$emit('change-group', this.groupData, this.keyIdx, true)
        },
        changeGroup(el) {
            let data ={}
            for (let i=0; i<this.groupOptions.length; i++) {
                if(this.groupOptions[i].id === el) {
                    data = JSON.parse(JSON.stringify(this.groupOptions[i]))
                    data.product.forEach(element => {
                        element.qty = element.dqty || element.dqty === 0 ? element.dqty : 1
                        delete element.product_lang
                        return element
                    })
                }
            }
            // this.groupData = data
            this.groupData.group_id = data.id
            this.groupData.product = data.product
            this.groupData.price = data.price
            this.groupData.scode = data.scode
            this.groupData.sale_name = data.sale_name
            this.groupData.mphoto = data.mphoto
            this.groupData.mphoto_url = data.mphoto_url
            this.groupData.is_available = data.is_available
            this.groupData.is_sale = data.is_sale
            this.groupData.content = data.content
            this.groupData.available_name = data.available_name
            this.groupData.description = data.description
            this.groupData.created_at = data.created_at
            this.groupData.omcategory = data.omcategory
            this.groupData.lang = data.lang
            this.groupData.area = data.area
            this.groupData.area_region_id = ''
            this.$emit('change-group', this.groupData, this.keyIdx, true)
        }
    }
}
</script>

<style>

</style>

